package com.beiding.workordersystem.common.utils;

import org.springframework.util.StreamUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

public class ResourceUtils {

    /**
     * 将输入流作为文件输出进行下载
     */
    public static void download(InputStream inputStream, String name) throws IOException {

        ServletRequestAttributes requestAttributes;
        HttpServletResponse response;
        if ((requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) == null || (response = requestAttributes.getResponse()) == null) {
            throw new RuntimeException("不在请求上下文中");
        }

        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");

        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
        } catch (Exception ignore) {
        }

        response.setStatus(200);

        ServletOutputStream outputStream = response.getOutputStream();

        //进行流复制
        StreamUtils.copy(inputStream, outputStream);

    }

    public static void downloadClassPathSource(String path,String name) throws IOException {
        download(getClassPathResource(path), name);
    }

    public static String classPathResourceAsString(String path) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        InputStream classPathResource = getClassPathResource(path);
        StreamUtils.copy(classPathResource, byteArrayOutputStream);
        classPathResource.close();
        return new String(byteArrayOutputStream.toByteArray());
    }

    public static InputStream getClassPathResource(String path) {
        return ResourceUtils.class.getClassLoader().getResourceAsStream(path);
    }

    public static void copyRequestBody(OutputStream outputStream) throws IOException {
        ServletRequestAttributes requestAttributes;
        HttpServletRequest request;
        if ((requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) == null) {
            throw new RuntimeException("不在请求上下文中");
        }
        request = requestAttributes.getRequest();
        StreamUtils.copy(request.getInputStream(), outputStream);
    }

}
